package org.altervista.cp.thinbcgen.bean;

import java.lang.reflect.Constructor;

import org.altervista.cp.thinbcgen.AbstractGenerator;

@SuppressWarnings("unchecked")
public class JavaBeanGenerator extends AbstractGenerator {

	public JavaBeanGenerator(Class targetClass, Object[] args) {
		this(targetClass);
	}

	public JavaBeanGenerator(Class targetClass) {
		super(targetClass, new Object[0]);
	}

	public Object generate() {
		String generatedClassName = _targetClass.getName() + "_" + "_JavaBean";
		Class generatedClass = ((JavaBeanGenerator) _realGen)
				.getGeneratedClass(generatedClassName, new Object[0]);
		try {
			return newInstance(generatedClass.getConstructor(new Class[0]),
					new Object[0]);
		} catch (Exception e) {
			throw new IllegalStateException(e);
		}
	}

	protected Constructor getGeneratorConstructor() {
		String packageName = JavaBeanGenerator.class.getPackage().getName();
		Constructor constructor = null;
		try {
			constructor = Class.forName(packageName + ".SunJavaBeanGenerator")
					.getDeclaredConstructor(GENERATOR_PARAM_TYPES);
		} catch (Exception e) {
			try {
				constructor = Class.forName(
						packageName + ".ApacheJavaBeanGenerator")
						.getDeclaredConstructor(GENERATOR_PARAM_TYPES);
			} catch (Exception ex) {
				throw new IllegalStateException(ex);
			}
		}
		constructor.setAccessible(true);
		return constructor;
	}

	private static final Class[] GENERATOR_PARAM_TYPES = new Class[] {
			Class.class, Object[].class };

	protected String getGeneratedSuffix() {
		return "JavaBean";
	}

}
